package com.snailct.bpp.service.client.support;

import com.snailct.bpp.service.client.ClientException;
import com.snailct.bpp.service.client.IServiceInvoker;
import com.snailct.bpp.commons.protocol.RespResult;
import com.snailct.bpp.commons.utils.JsonUtils;
import com.snailct.bpp.commons.utils.PropertiesUtil;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Map;


abstract class DefaultServiceInvoker implements IServiceInvoker {
    protected final Log logger = LogFactory.getLog(getClass());
    private static final String JSON_REQUEST_HEADER = "header";
    private static final String JSON_REQUEST_BODY = "body";
    private String reqURL;
    public RespResult invoke(String sendData) throws ClientException {
        //组装成平台格式的XML报文
        String reqDataXML = constructReqData(sendData);
        setReqURL(PropertiesUtil.getPropValue("wsurl"));
        return request(reqDataXML);

    }
    protected abstract RespResult request(String reqXml);

    private String constructReqData(String sendData){
        JSONObject reqJson = JSONObject.fromObject(sendData);
        String reqHdr = reqJson.getString(JSON_REQUEST_HEADER);
        String reqBody = reqJson.getString(JSON_REQUEST_BODY);
        JSONObject requestHeader = JSONObject.fromObject(reqHdr);
        Map<String, Object> params = JsonUtils.getDTOMap(reqBody);

        StringBuilder reqXml = getReqXml(requestHeader, params);
        return reqXml.toString();
    }
    private StringBuilder getReqXml(JSONObject requestHeader, Map<String, Object> params) {
        String business = requestHeader.getString("business");
        StringBuilder reqXml = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        reqXml.append("<reqData>");
        reqXml.append("<header>");
        reqXml.append("<serviceId>" + business + "</serviceId>");
        reqXml.append("<serviceType>HTTP</serviceType>");
        reqXml.append("<respParamType>java.lang.String</respParamType>");
        reqXml.append("</header>");
        reqXml.append("<body>");
        reqXml.append("<reqParams>");
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                reqXml.append("<reqParam>");
                reqXml.append("<fieldName>" + entry.getKey() + "</fieldName>");
                reqXml.append("<fieldValue>" + entry.getValue() + "</fieldValue>");
                reqXml.append("</reqParam>");
            }
        }
        reqXml.append("</reqParams>");
        reqXml.append("</body>");
        reqXml.append("</reqData>");
        if (logger.isDebugEnabled()) {
            logger.debug("req xml=" + reqXml);
        }
        return reqXml;
    }

    protected String getReqURL() {
        return reqURL;
    }

    private void setReqURL(String reqURL) {
        this.reqURL = reqURL;
    }
}
